package com.cj.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.cj.mapper.ArticleMapper;
import com.cj.pojo.Article;
import com.cj.pojo.PageBean;
import com.cj.service.ArticleService;
import com.cj.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {
    private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImpl.class);

    @Autowired
    private ArticleMapper articleMapper;

    @Override
    public void add(Article article) {
        //补充属性值
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());

        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        article.setCreateUser(userId);

        articleMapper.add(article);
    }

    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state, Integer requestUserId) {
        //1.创建PageBean对象
        PageBean<Article> pb = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        //3.调用mapper
        @SuppressWarnings("unchecked")
        Map<String,Object> claims = (Map<String,Object>) ThreadLocalUtil.get();
        Integer userId = requestUserId != null ? requestUserId : (Integer) claims.get("id");
        logger.info("查询文章列表参数 - userId: {}, categoryId: {}, state: {}, pageNum: {}, pageSize: {}", 
            userId, categoryId, state, pageNum, pageSize);
        List<Article> as = articleMapper.list(userId,categoryId,state);
        logger.info("查询结果数量: {}, 总记录数: {}", as.size(), ((Page<Article>) as).getTotal());
        //Page中提供了方法,可以获取PageHelper分页查询后 得到的总记录条数和当前页数据
        Page<Article> p = (Page<Article>) as;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    @Override
    @Transactional
    public void batchDelete(List<Long> ids) {
        if (ids != null && !ids.isEmpty()) {
            articleMapper.batchDelete(ids);
        }
    }

    @Override
    public PageBean<Article> search(String keyword, Integer pageNum, Integer pageSize) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'search'");
    }

    @Override
    public void view(Long id) {
        // TODO Auto-generated method stub
        throw new UnsupportedOperationException("Unimplemented method 'view'");
    }
}
